//-----------------------------------------------
//hook sleep
//对系统函数sleep进行hook
//开一个线程，两个任务的sleep同时运行了
//同步方式 实现 异步性能
#include "hook.h"
#include "log.h"

namespace tt01{

learnco::Logger::ptr g_logger = learnco::LoggerMgr::GetInstance()->getLogger("user");


void test_sleep() {
    learnco::IOmanger iom(1,"poll", false);
    LEARNCO_LOG_DEBUG(g_logger) << "观察开始时间...";

    iom.scheduler([](){
        sleep(2);
        LEARNCO_LOG_DEBUG(g_logger) << "sleep 2";
    });

    iom.scheduler([](){
        sleep(5);
        LEARNCO_LOG_DEBUG(g_logger) << "sleep 5";
    });
}

}//namespace 
//-----------------------------------------------


//-----------------------------------------------
//hook socket
//对系统函数socket相关函数进行hook异步化改造
//同步方式 实现 异步性能
#include <sys/socket.h>
#include <netdb.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

#include "hook.h"
#include "log.h"

namespace tt02{

learnco::Logger::ptr g_logger = learnco::LoggerMgr::GetInstance()->getLogger("user");


void test_socket() {

    learnco::IOmanger iom(1,"poll", false);
    iom.scheduler([](){

        int sock = socket(AF_INET, SOCK_STREAM, 0);

        sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(80);
        inet_pton(AF_INET, "36.152.44.96", &addr.sin_addr.s_addr);

        LEARNCO_LOG_DEBUG(g_logger) << "begin connect";
        int rt = connect(sock, (const sockaddr*)&addr, sizeof(addr));
        LEARNCO_LOG_DEBUG(g_logger) << "connect rt=" << rt << " errno=" << errno;

        if(rt) {
            return;
        }

        const char data[] = "GET / HTTP/1.0\r\n\r\n";
        rt = send(sock, data, sizeof(data), 0);
        LEARNCO_LOG_DEBUG(g_logger) << "send rt=" << rt << " errno=" << errno;

        if(rt <= 0) {
            return;
        }

        std::string buf;
        buf.resize(40960);

        rt = recv(sock, &buf[0], buf.size(), 0);
        
     
        LEARNCO_LOG_DEBUG(g_logger) << "recv rt=" << rt << " errno=" << errno;

        if(rt <= 0) {
            return;
        }

        buf.resize(rt);
        LEARNCO_LOG_DEBUG(g_logger) << buf;
    });
    
}

}//namespace 
//-----------------------------------------------




int main()
{
    //tt01::test_sleep();
    tt02::test_socket();
    
    return 0;
}